import { TUIConversationService } from '@tencentcloud/chat-uikit-engine'
import { useUserStore } from '@/stores/user'
import { TUILogin } from '@tencentcloud/tui-core'
import { useLogin } from '@/stores/login'

/**
 * 跳转聊天页面
 * @param jumpType 跳转类型 1 正常跳转 2产品跳转 3订单跳转
 * @param typeId 产品或订单的id
 * @param shopId 店铺id
 */
// factory-1
export const jumpChat = async (ImId: string, isShop = false) => {
    if (!ImId) {
        uni.showToast({
            title: '该用户没有IM账号',
            icon: 'none'
        })
        return
    }
    // 登录im
    const IMRes = await loginIm()

    if (!IMRes) {
        return
    }

    const id = isShop ? 'factory-' + ImId : ImId

    console.log('---------', id)
    uni.navigateTo({
        url: '/TUIKit/components/TUIChat/index'
    })
    // 切换会话 C2C + userId
    TUIConversationService.switchConversation('C2C' + id)
}

export async function loginIm() {
    const { getUser, token, getImInfo, imInfo: im } = useUserStore()
    console.log('im============', im, token)

    if (!token) {
        const loginStore = useLogin()
        loginStore.showLogin = true
        return false
    }

    let imInfo = im
    if (!im) {
        await getImInfo()
        imInfo = im || useUserStore().imInfo

        // IM 登录
    }
    console.log('im登录')
    // console.log(err)
    //
    // uni.showToast({
    //     title: err + '',
    //     icon: 'none'
    // })

    const IMRes = await TUILogin.login({
        SDKAppID: imInfo.config.sdkAppId && Number(imInfo.config.sdkAppId),
        userID: imInfo.account.userId,
        userSig: imInfo.account.userSig,
        // SDKAppID: uni.$SDKAppID,
        // userID: uni.$userID,
        // userSig: uni.$userSig,
        useUploadPlugin: true, // If you need to send rich media messages, please set to true.
        framework: `vue${3}` // framework used vue2 / vue3
    })
    console.log('登录成功', IMRes)

    return true
}
